package com.haierCamera.customapplication.ui.custom;

import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.databinding.ViewDataBinding;
import androidx.viewpager.widget.PagerAdapter;

/**
 * @author yawei
 * @data on 2018/7/19 上午10:23
 * @email zyawei@live.com
 */
public abstract class DataBoundPagerAdapter<T, V extends ViewDataBinding> extends PagerAdapter {

    private List<T> data;
    private final SparseArray<V> caches = new SparseArray<>();

    public DataBoundPagerAdapter() {
    }


    public void replace(@NonNull List<T> data) {
        this.data = data;
    }

    protected abstract void bindViewBinding(V viewBinding, T data);

    protected abstract V createBinding(ViewGroup viewGroup, int position);


    @Override
    public int getCount() {
        return Integer.MAX_VALUE;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        int realPosition = position % data.size();
        V binding = caches.get(realPosition);
        if (binding == null) {
            binding = createBinding(container, position);
            caches.put(realPosition,binding);
        }
        container.addView(binding.getRoot());
        bindViewBinding(binding, data.get(realPosition));
        return binding.getRoot();
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }
}
